package fun.yyds.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.ip.udp.MulticastReceivingChannelAdapter;
import org.springframework.integration.ip.udp.MulticastSendingMessageHandler;

import java.nio.charset.StandardCharsets;
// I have tried using administrator mode to start the program, switched multiple different IPs and ports, and closed the firewall. The startup parameter has been added with - Djava.net.refererIPv4Stack=true
@Configuration
public class UDPConfig {

    private static final String MULTICAST_ADDRESS = "224.1.1.101";
    private static final int PORT = 12345;

    @Bean
    public MulticastReceivingChannelAdapter multicastAdapter() {
        MulticastReceivingChannelAdapter adapter =
                new MulticastReceivingChannelAdapter(MULTICAST_ADDRESS, PORT);
        adapter.setOutputChannelName("udpChannel");
        return adapter;
    }

    @Bean
    public MulticastSendingMessageHandler messageHandler() {
        return new MulticastSendingMessageHandler("224.1.1.100", 12345);
    }

    @Bean
    public IntegrationFlow udpInboundFlow(ObjectMapper objectMapper) {
        return IntegrationFlows.from("udpChannel")
                .transform(payload -> new String((byte[]) payload, StandardCharsets.UTF_8)) // 字节转字符串
                .<String, String>transform(json ->
                        {
                            try {
                                return objectMapper.readValue(json, String.class);
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }
                        } // 解析JSON
                )
                .handle(message -> {
                    String str = (String) message.getPayload();
                    System.out.println("解析结果: " + str);
                })
                .get();
    }
}
